<template>
  <div class="common-wrapper">
    <div class="common-search">
      <a-button
        icon="plus"
        type="danger"
        style="background: #13c2c2; border-color: #13c2c2; margin-right: 20px"
        @click="openDialog('add')"
      >
        添加
      </a-button>
      <a-form layout="inline">
        <a-form-item label="员工姓名">
          <a-input v-model="search.name" />
        </a-form-item>
        <a-form-item label="员工工号">
          <a-input v-model="search.work_number" />
        </a-form-item>
      </a-form>
      <a-button type="primary" @click="getTableData(1)"> 搜索 </a-button>
      <a-upload :showUploadList="false" :before-upload="beforeUpload" :customRequest="selfUpload">
        <a-button type="danger" style="margin-left:10px"> 导入 </a-button>
      </a-upload>
      <a href="/员工模板.xlsx" style="margin-left:10px" download="员工模板.xlsx">模板下载</a>
    </div>
    <div class="common-main" ref="main">
      <a-table
        size="middle"
        rowKey="id"
        :columns="columns"
        :data-source="dataSource"
        bordered
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template slot="floatTime" slot-scope="text">
          <span>{{ text }}分钟</span>
        </template>
        <template slot="action" slot-scope="text, record">
          <a-button type="link" @click="openDialog('edit', record)">编辑</a-button>
          <a-popconfirm title="是否确定删除该员工？" ok-text="确定" cancel-text="取消" @confirm="delStaff(record.id)">
            <a href="#">删除</a>
          </a-popconfirm>
        </template>
      </a-table>
    </div>
    <!-- modal -->
    <a-modal :title="modalType == 'add' ? '添加' : '编辑'" :visible="visible" @cancel="handleCancel">
      <a-form-model ref="form" :model="form" :rules="rules">
        <a-form-model-item label="员工工号" prop="work_number" :colon="false">
          <a-input v-model="form.work_number" :disabled="modalType == 'edit'" />
        </a-form-model-item>
        <a-form-model-item label="员工姓名" prop="name" :colon="false">
          <a-input v-model="form.name" />
        </a-form-model-item>
        <a-form-model-item label="浮动时间" prop="work_time_float" :colon="false">
          <a-input type="number" v-model="form.work_time_float" />
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="submitStaff">确定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { getSpecialTableData, setSpecialStaff, delSpecialStaff, importUser } from '@/api/attendance'
export default {
  data () {
    const columns = [
      {
        title: '员工姓名',
        dataIndex: 'name',
        align: 'center',
        width: '20%'
      },
      {
        title: '员工工号',
        dataIndex: 'work_number',
        align: 'center',
        width: '20%'
      },
      {
        title: '添加时间',
        dataIndex: 'create_time',
        align: 'center',
        width: '20%'
      },
      {
        title: '浮动时间',
        dataIndex: 'work_time_float',
        align: 'center',
        width: '20%',
        scopedSlots: { customRender: 'floatTime' }
      },
      {
        title: '操作',
        width: 120,
        align: 'center',
        scopedSlots: { customRender: 'action' }
      }
    ]
    const validateFloat = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入浮动时间'))
      } else if (!new RegExp('^[1-9][0-9]*$').test(value)) {
        callback(new Error('请输入有效浮动时间'))
      } else {
        callback()
      }
    }
    return {
      search: {
        name: '',
        work_number: '',
        pageIndex: 1,
        pageSize: 8
      },
      columns,
      /* 分页参数 */
      pagination: {
        current: 1,
        pageSize: 8,
        showTotal: (total, range) => {
          return ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: false,
        total: 0
      },
      loading: false,
      dataSource: [],
      /* modal */
      modalType: 'add',
      visible: false,
      form: {
        name: '',
        work_number: '',
        work_time_float: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入员工姓名', trigger: 'blur' },
          { min: 1, max: 5, message: '长度不可超过5个', trigger: 'blur' }
        ],
        work_number: [{ required: true, message: '请输入员工工号', trigger: 'blur' }],
        work_time_float: [{ required: true, validator: validateFloat, trigger: 'blur' }]
      }
    }
  },
  mounted () {
    this.resize()
    window.addEventListener('resize', this.resize)
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.resize)
  },
  methods: {
    async resize () {
          this.getPageSize()
          await this.getTableData()
    },
    // 获取表格
    async getTableData (cur) {
      if (cur == 1) {
        this.search.pageIndex = cur
        this.pagination.current = cur
      } else {
        this.search.pageIndex = this.pagination.current
      }
      const { data } = await getSpecialTableData(this.search)
      this.dataSource = data.items
      this.pagination.total = data.totalCount
    },
    // 新增/编辑人员
    submitStaff () {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          const res = await setSpecialStaff([this.form])
          if (res.succeeded) {
            this.$message.success('操作成功')
            this.getTableData(1)
            this.handleCancel()
          }
        }
      })
    },
    // 删除员工
    async delStaff (id) {
      const res = await delSpecialStaff({ id: id })
      if (res.succeeded) {
        this.$message.success('删除成功')
        this.getTableData(1)
      }
    },
    getPageSize () {
      const height = this.$refs.main.offsetHeight - 68 - 30
      const pageSize = Math.floor(height / 50)
      this.search.pageSize = pageSize
      this.pagination.pageSize = pageSize
    },
    openDialog (type, record) {
      this.modalType = type
      if (record) {
        this.form = {
          name: record.name,
          work_number: record.work_number,
          work_time_float: record.work_time_float
        }
      }
      this.visible = true
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = pagination
      this.getTableData()
    },
    handleCancel () {
      this.visible = false
      this.form = {
        name: '',
        work_number: '',
        work_time_float: ''
      }
      this.$refs['form'].resetFields()
    },
    beforeUpload (file) {
      if (
        file.type !== 'application/vnd.ms-excel' &&
        file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      ) {
        this.$message.error('文件格式错误，只能选择.xls或.xlsx文件')
        return false
      }
      return file
    },
    selfUpload ({ action, file, onSuccess, onError, onProgress }) {
      console.log(file)
      const formData = new FormData()
      formData.append('excel', file)

      importUser(formData)
        .then((res) => {
          if (res.statusCode === 200) {
            this.$message.success('导入成功')
            this.getTableData(1)
          } else {
            this.$message.error(res.errors)
          }
        })
        .catch(() => {
          this.$message.error('上传失败，请重新上传！')
        })
    }
  }
}
</script>

<style lang="less">
.common-wrapper {
  height: 100%;
  padding: 20px;
}
.common-search {
  padding-bottom: 10px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #efefef;
}
.common-main {
  height: calc(100% - 50px);
  padding-top: 10px;
  .ant-table .ant-btn {
    height: 24px;
    line-height: 24px;
  }
}
</style>
